package com.five.monkey.feign.es.config;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

/**
 * @author 狻猊
 * @desc elasticsearch configuration
 * @date 2022-03-29 20:10:29
 */
@Configuration
@EnableElasticsearchRepositories(basePackages = {"com.five.monkey.feign.es.dao.repository"}, elasticsearchTemplateRef = "elasticsearchRestTemplate")
public class ElasticsearchConfig {

    @Value("${elasticsearch.rest.uris}")
    private String uris;

    @Bean(destroyMethod = "close")
    public RestHighLevelClient restHighLevelClient() {
        String[] uriArray = StringUtils.split(uris, ",");
        HttpHost[] httpHosts = new HttpHost[uriArray.length];
        for (int i = 0; i < uriArray.length; i++) {
            httpHosts[i] = HttpHost.create(uriArray[i]);
        }
        return new RestHighLevelClient(RestClient.builder(httpHosts));
    }

    @Bean
    @ConditionalOnBean(RestHighLevelClient.class)
    public ElasticsearchOperations elasticsearchRestTemplate(RestHighLevelClient elasticsearchNode1Client) {
        return new ElasticsearchRestTemplate(elasticsearchNode1Client);
    }
}
